package com.zwcl.common.component.notice.service;

import com.zwcl.common.core.constant.Constants;
import com.zwcl.common.core.utils.StringUtilsEx;
import com.zwcl.common.component.notice.config.NoticeMailConfig;
import com.zwcl.common.component.notice.service.mail.MailSenderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Description 警告service，目前仅邮件警告
 * @Author tanljs
 * @Date 2019/10/15
 * @Email Alex.tan@wetax.com.cn
 * @version V1.0.6
 */
@Slf4j
@Component
public class WarnService {

    @Value("${notice.warnEnable}")
    private boolean warnEnable;

    @Autowired
    private NoticeMailConfig noticeMailConfig;

    @Autowired
    private MailSenderService mailSenderService;

    @Value("${spring.profiles.active}")
    private String env;

    @Value("${spring.application.name:unknown}")
    private String application;

    private static final String warnTile = "[java][中网车联]";

    /**
     * 异常警告
     * @param e 异常
     */
    public void warnFromException(Exception e) {
        warnFromException(e, null);
    }

    public void warnFromException(Exception e, String title) {
        if (StringUtilsEx.isNoneBlank(e.getMessage())) {
            StringBuilder sb = new StringBuilder();
            try {
                sb.append("IP：").append(InetAddress.getLocalHost().getHostAddress()).append("<br/>");
            } catch (UnknownHostException ex) {}

            try {
                HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
                sb.append("URL    ：").append(request.getRequestURL()).append("<br/>");
                sb.append("Method ：").append(request.getMethod()).append("<br/>");
                sb.append("token  ：").append(request.getHeader(Constants.AUTHORIZE_TOKEN)).append("<br/>");
            } catch (Exception ex) {}

            sb.append("异常信息：").append(e.getMessage()).append("<br/>");
            sb.append("异常stack：");
            for (StackTraceElement se : e.getStackTrace()) {
                sb.append(se).append("<br/>");
            }
            warn(StringUtils.isBlank(title)?e.getMessage():title, sb.toString());
        }
    }

    /**
     * 文字警告
     * @param title 邮件标题
     * @param warnContent 邮件正文
     */
    public void warn(String title, String warnContent) {
        if (warnEnable) {
            if (noticeMailConfig == null) {
                log.warn("没有配置告警邮箱！");
            } else {
                mailSenderService.sendEmailAsync("["+env+"]" + warnTile + "["+application+"]" + title, noticeMailConfig.getList(), warnContent);
            }
        }
    }
}
